package org.example.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class WXDecryptUtil {

    /**
     * 解密微信加密数据
     *
     * @param encryptedData 加密数据
     * @param sessionKey    会话密钥
     * @param iv            偏移量
     * @return 解密后的用户信息
     */
    public static String decrypt(String encryptedData, String sessionKey, String iv) {
        try {
            byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
            byte[] sessionKeyBytes = Base64.getDecoder().decode(sessionKey);
            byte[] ivBytes = Base64.getDecoder().decode(iv);

            SecretKeySpec secretKeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes));

            byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);
            //  返回解密后的用户信息
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解密失败", e);
        }
    }
}